var permissionTree;
var orgTree;
var permForPermManageTree;
var menuLength=getLength("config_page_size");
var permissionSetting = {
	check: {
		enable: true,
		chkboxType: {
			"Y":"ps", "N":"ps"
		},
		chkStyle:"checkbox"
	},
	view: {
		selectedMulti: true
	},
	data: {
		simpleData: {
			enable: true,
			idKey:"PERM_ID",
			pIdKey:"PARENT_ID"
		},
		key:{
			name:"PERM_NAME"
		}
	},	
	callback: {
		beforeClick: function(treeId, treeNode) {
		},
		onCheck:setPermData
		
	}
};
var permForPermManageSetting = {
		check: {
			enable: true,
			chkboxType: {
				"Y":"ps", "N":"ps"
			},
			chkStyle:"checkbox"
		},
		view: {
			selectedMulti: true
		},
		data: {
			simpleData: {
				enable: true,
				idKey:"PERM_ID",
				pIdKey:"PARENT_ID"
			},
			key:{
				name:"PERM_NAME"
			}
		},	
		callback: {
			beforeClick: function(treeId, treeNode) {
			}
			
		}
	};
var permissionViewSetting = {
		view: {
			selectedMulti: false
		},
		data: {
			simpleData: {
				enable: true,
				idKey:"PERM_ID",
				pIdKey:"PARENT_ID"
			},
			key:{
				name:"PERM_NAME"
			}
		},	
		callback: {
			beforeClick: function(treeId, treeNode) {
			}
		}
	};
//组织树设置
var orgSetting = {
	view: {
		selectedMulti: false
	},
	data: {
		simpleData: {
			enable: true,
			idKey:"oCode", 
            pIdKey:"pCode"
		}
	},
	callback: {
		beforeClick: function(treeId, treeNode) {
			$('#orgId').val(treeNode.id);
			$('#orgName').val(treeNode.name);
			$('#orgId').change();
			$('#orgCloseModal').click();
		}
	},
	async:{
		enable: true,
		url:"../sysOrgController/disOrgTree",
		autoParam:["oCode","has_bm","orgKind"]
	}
};


var setting = {
		view : {
			selectedMulti : true
		// 设置是否允许同时选中多个节点
		},
		edit : {
			enable : false, // 设置 zTree 是否处于编辑状态
			editNameSelectAll : false, // 节点编辑名称 input 初次显示时,设置 txt
										// 内容是否为全选状态
		},
		data : {
			simpleData : {
				enable : true
			// 确定 zTree 初始化时的节点数据、异步加载时的节点数据、或 addNodes 方法中输入的 newNodes
			// 数据是否采用简单数据模式 (Array)
			}
		},
		check : {
			chkStyle : "checkbox",// 勾选框类型
			enable : true, // 设置 zTree 的节点上是否显示 checkbox
			chkboxType : {
				"Y" : "",
				"N" : ""
			}
		},
/*		callback:{
			onCheck :function(e, treeId, treeNode) {
				var treeObj = $.fn.zTree.getZTreeObj("stafftree");
				nodes = treeObj.getCheckedNodes(true);
				for (var i = 0; i < nodes.length; i++) {
					$("#jinggao").html("");
					if (nodes[i].isParent) {
						$("#jinggao").html("组织节点不可选！");
						treeObj.cancelSelectedNode(nodes[i]);
						treeObj.checkNode(nodes[i]);
					//	return;
					}	
				}
		}},*/
		async : {
			enable : true,
			url : "../gacxOrgController/loadStaffTreeData?t=" + (new Date().getTime()),
			autoParam : [ "id=pid"],
			dataFilter: filterStaff //处理异步加载返回的数据
		}
	};

function filterStaff(treeId, parentNode, childNodes) {
	var roleId = $("#showStaffInRoleId").val();
	var array = new Array();
	$.ajax({
		url:"../gacxRoleController/selectStaffInRole.action",
		data:{'roleId':roleId},
		dataType:"JSON",
		type:"POST",
		async:false,
		success:function(data){
			if(data.length<0){
				for(i=0;i<childNodes.length;i++){
					if("true" == childNodes[i].isParent){
						array.push(childNodes[i]);		 
					}else{
						for(j=0;j<data.length;j++){
							 if((childNodes[i].id).replace("u","") == data[j].STAFF_ORG_ID){	
									 break;
							 }else if(j==data.length-1){
								 array.push(childNodes[i]);	
							 }
						 }	
					} 
				 }
				 childNodes=array;
			}
			 
			
		 }
		
	});
	
	return childNodes;
}
$(function(){
	// 加载表格
	searchTable = $("#searchTable").DataTable(dataTableConfig);
	initFrame();
	//searchTable.ajax.reload();
});
var btnModel = '    \
	{{#each func}}\
    <button type="button" class="user-button user-{{this.type}} btn-sm" onclick="{{this.fn}}">{{this.name}}</button>\
    {{/each}}';
var template = Handlebars.compile(btnModel);
var searchTable;
function btnFun(c){
	contentBtn = "";
	if(contentBtn){
		return contentBtn;
	}else{
		var btnArray = new Array();
		if(hadPermission.update){
			btnArray.push( {"name": "修改", "fn": "showEditPage(\'" + c.roleId + "\')"});
		}
		if(hadPermission.del){
			btnArray.push({"name": "删除", "fn": "del(\'" + c.roleId + "\',\'" + c.roleName + "\',\'" + c.orgName + "\')", "type": "btn-n"});
		}
		if(hadPermission.getPerm){
			btnArray.push({"name": "查看权限", "fn": "searchPerm(\'" + c.roleId + "\', \'"+ c.roleName +"\')"});
		}
		if(hadPermission.getStaff){
			btnArray.push({"name": "关联人员", "fn": "searchStaff(\'" + c.roleId + "\', \'"+ c.roleName +"\')"});
		}
		contentBtn = {
			func:btnArray
		}
		return contentBtn;
	}
	
}
var dataTableConfig = {
		"ordering": false,// 排序
		"serverSide": true,// 开启服务器模式
		"scrollX": true,// 横向滚动
		"paging":true,
		ajax: {
	        "type": "POST",
	        "url":'newsearch4Page.action',//请求路径
	        "contentType": 'application/x-www-form-urlencoded; charset=UTF-8',
	        "dataType":'json',
	        "data":function(d){// 查询参数
	        	d.ROLE_NAME = $('#sysRoleName').val();
	        	d.ORG_NAME = $('#sysOrgName').val();
	        	return d;
	        }
		},            
		columns: [// 对应列
	        {"data": null,title:"操作",className: "text-center","width":"20%"},
	        {"data": "roleName",title:"角色名",className: "text-center",render : $.fn.dataTable.render.ellipsis(22, true)},
	        {"data": "roleDesc",title:"角色描述",className: "text-center",render : $.fn.dataTable.render.ellipsis(22, true)},
	        {"data": "createDate",title:"添加时间",className: "text-center",render : $.fn.dataTable.render.ellipsis(22, true)}
	    ],
	    "columnDefs": [
			{// 所有列默认值
				"targets": "_all",
				"defaultContent": ''
			},
	       {// 最后一列添加按钮
	        targets: 0,
	        render: function (a, b, c, d) {
	        	 var context = btnFun(c);
	             var html = template(context);
	             return html;
	        }
	    }],
	    lengthMenu: [
	    	menuLength,
	    	menuLength
	    ],
	    "dom": 'rt<"pull-left mt5"l><"pull-left mt5"i><"pull-right mt5"p><"clear">' //生成样式
	};
function initFrame(){
	$('#searchContent').show();
	$('#roleModal').hide();
	$('#orgModal').modal("hide");
	$('#RoleContainer').hide();
	$('#addBtn').hide();
	$('#updateBtn').hide();
	$('#roleForm input').val('');
	$('#roleForRoleManage').hide();
	$('#permForPermManage').hide();
	$('.roleChoose').remove();
	$('#roleList button').remove();
	resetValidator();
}
function searchRole(){
	searchTable.ajax.reload();
}
function reset(){
	$('#sysRoleName').val("");
	$('#sysOrgName').val("");
	
}
//显示添加角色
function addRoleShow(){
	$('#roleManage').hide();
	$('#searchContent').hide();
	$('#roleForm input').val('');
	$('#roleModal').show();
	$('#roleModalTitle').text("新增角色");
	$('#updateBtn').hide();
	$.post("getRoleByPermData.action",function(data){
		$html ="<button type=\"button\" class=\"user-button btn-sm\" onclick=\"chooseAll()\">全选</button>"
			  + "<button type=\"button\" class=\"user-button user-btn-n btn-sm\" onclick=\"clearAll()\">清除</button>"
		$("#roleList").append($html); 
		for(var i=0;i<data.roleList.length;i++){
			$html = "<label class=\"roleChoose\">" + "<input type=\"checkbox\" name=\"roleList\" value=\""+data.roleList[i].roleId+"\"/>"
			+ "<span>"+data.roleList[i].roleName+"</span></label>";
			$("#roleList").append($html);
		}
	})
	//加载组织树和权限树
	$.post("LoadTreeData.action",function(data){
		permissionTree = $.fn.zTree.init($("#permissionTree"), permissionSetting, data.permTree);
		orgTree = $.fn.zTree.init($("#orgTree"), orgSetting, data.orgTree);
		permForPermManageTree = $.fn.zTree.init($("#permForPermManageTree"), permForPermManageSetting, data.permTree);
	});
	$('#addBtn').show();
	if(null == $('#roleForm').data('bootstrapValidator')) {
		$('#roleForm').bootstrapValidator(checkValidator);
	}
	resetValidator();
    $('#orgId').on('change', function(e) {
        $('#roleForm')
            .data('bootstrapValidator')
            .updateStatus('orgId', 'NOT_VALIDATED', null)
            .validateField('orgId');
    });
    
}
//设置添加角色时拥有权限管理或角色管理的数据范围
function setPermData(){
	var treeObj = $.fn.zTree.getZTreeObj("permissionTree");
	var node1 = treeObj.getNodeByParam("PERM_ID", 100);
	var node2 = treeObj.getNodeByParam("PERM_ID", 201);
	if(node1.checked){
		$('#permForPermManage').show();
	}
	if(node2.checked){
		$('#roleForRoleManage').show();
	}
	if(!node1.checked){
		$('#permForPermManage').hide();
		var permForPermManageTreeObj = $.fn.zTree.getZTreeObj("permForPermManageTree");
		permForPermManageTreeObj.checkAllNodes(false);
	}
	if(!node2.checked){
		$('#roleForRoleManage').hide();
		
	}
}
//添加角色至后台
function addRole(){
	//获取角色的权限
	var permissionTreeObj = $.fn.zTree.getZTreeObj("permissionTree");
	var node1 = permissionTreeObj.getNodeByParam("PERM_ID", 100);
	var node2 = permissionTreeObj.getNodeByParam("PERM_ID", 201);
	var permissionTreeNodes = permissionTreeObj.getCheckedNodes(true);
	var permId = '';
	for(var i = 0 ; i < permissionTreeNodes.length; i++){
		permId += permissionTreeNodes[i].PERM_ID;
		permId += ",";	
	}
	//获取角色拥有权限“权限管理”时可操作的权限
	var permForPermManageTreeObj = $.fn.zTree.getZTreeObj("permForPermManageTree");
	var permForPermManageNodes = permForPermManageTreeObj.getCheckedNodes(true);
	//当角色拥有权限“权限管理”但是没有选择可操作的权限时弹框提示
	if(node1.checked &&permForPermManageNodes.length<=0){
		alertModel("请选择该角色权限管理时可操作的权限");
		return;
	}else{
		var permForPermManageId = '';
		for(var i = 0 ; i < permForPermManageNodes.length; i++){
			permForPermManageId += permForPermManageNodes[i].PERM_ID;
			permForPermManageId += ",";	
		}
	}
	//获取角色拥有权限“角色管理”时可操作的角色
	 var roleForRoleManageObj = document.getElementsByName("roleList");
	 var roleForRoleManageId = "";
	 for(var i=0; i<roleForRoleManageObj.length; i++){
        if(roleForRoleManageObj[i].checked){
        	roleForRoleManageId += roleForRoleManageObj[i].value;
        	roleForRoleManageId += ",";	
        }
    }
	if(node2.checked &&roleForRoleManageId.length<=0){
		alertModel("请选择该角色角色管理时可操作的角色");
		return;
	}
	var roleName = $('#roleName').val();
	var orgName = $('#orgName').val();
	//var orgId = $('#orgId').val();
	var roleDesc =$('#roleDesc').val();
	$.ajax({
		url:"addSysRole.action",
		cache:false, 
		data:{permId:permId,
			roleDesc:roleDesc,
			roleName:roleName,
			orgId:0,
			permForPermManageId:permForPermManageId,
			roleForRoleManageId:roleForRoleManageId},
		dataType:"text",
		type:"POST",
		success:function(data){
			if(data=='success'){
				initFrame();
				permissionTree = null;
				searchTable.ajax.reload();
				alertModel("添加成功！");
			}
		},
		error:function(e){
			alertModel("添加失败o_o请重试...");
		}
	})
}
function backSearch1(){
	$('#permissionTree').val();
	$('.roleChoose').remove();
	$('#roleList button').remove();
	initFrame();
}


//展示修改页面
function showEditPage(roleId){
	$('#roleManage').hide();
	$('#searchContent').hide();
	$('#updateBtn').show();
//	$('#roleModal').modal({'show':true});
	$('#roleModal').show();
	$('#roleModalTitle').text("修改角色");
	$('#addBtn').hide();
	//插叙角色树和权限树
	$.post("LoadTreeData.action",function(data){
		permissionTree = $.fn.zTree.init($("#permissionTree"), permissionSetting, data.permTree);
		orgTree = $.fn.zTree.init($("#orgTree"), orgSetting, data.orgTree);	
		permForPermManageTree = $.fn.zTree.init($("#permForPermManageTree"), permForPermManageSetting, data.permTree);
		$.post("getRoleByPermData.action",function(data){
			$html ="<button type=\"button\" class=\"user-button btn-sm\" onclick=\"chooseAll()\">全选</button>"
			  + "<button type=\"button\" class=\"user-button user-btn-n btn-sm\" onclick=\"clearAll()\">清除</button>"
			$("#roleList").append($html);  
			for(var i=0;i<data.roleList.length;i++){
				$html = "<label class=\"roleChoose\">" 
					  + "<input type=\"checkbox\" name=\"roleList\" value=\""+data.roleList[i].roleId+"\"/>"
				+ "<span>"+data.roleList[i].roleName+"</span></label>";
				$("#roleList").append($html);
			}
		})
		$.post('searchRoleById.action',{roleId:roleId},function(data){
			var sysRole = data.sysRole;
			$('#roleId').val(sysRole.roleId);
			$('#roleName').val(sysRole.roleName);//角色名称
			$('#roleDesc').val(sysRole.roleDesc);//角色描述
			$('#orgName').val(data.orgName);//所属部门
			$('#orgId').val(sysRole.orgId);
			$('.upfpanel-title').text("角色修改");
//			var sysRolePermission = data.sysRolePermission;
			var permissionTreeObj = $.fn.zTree.getZTreeObj("permissionTree");
			var permForPermManageTreeObj = $.fn.zTree.getZTreeObj("permForPermManageTree");
			var permId = data['permId'];
			var permForPermManageId = data['permForPermManageId'];
			var roleForRoleManageId = data['roleForRoleManageId'];
			if(permId!=null){
				for (var i=0; i < permId.length; i++) {
					if(permId[i]==100){
						$('#permForPermManage').show();
					}
					if(permId[i]==201){
						$('#roleForRoleManage').show();
					}
					if(permissionTreeObj.getNodeByParam("PERM_ID",permId[i]))
						permissionTreeObj.checkNode(permissionTreeObj.getNodeByParam("PERM_ID",permId[i]), true);
			     }
			}
			if(permForPermManageId!=null){
				$('#permForPermManage').show();
				for (var i=0; i < permForPermManageId.length; i++) {
					if(permForPermManageTreeObj.getNodeByParam("PERM_ID",permForPermManageId[i]))
						permForPermManageTreeObj.checkNode(permForPermManageTreeObj.getNodeByParam("PERM_ID",permForPermManageId[i]), true);
			     }
			}
			if(roleForRoleManageId!=null&&roleForRoleManageId!=roleId){
				$('#roleForRoleManage').show();		
				var checkBoxAll = $("input[name='roleList']");
				for(var i=0;i<roleForRoleManageId.length;i++){
		           //获取所有复选框对象的value属性，然后，用roleForRoleManageId[i]和他们匹配，如果有，则说明他应被选中
		           $.each(checkBoxAll,function(j,checkbox){
		              //获取复选框的value属性
		              var checkValue=$(checkbox).val();
		              if(roleForRoleManageId[i]==checkValue){
		            	  $(checkbox).prop("checked",true);
		              }
		           })
		        }
			}
			if(null == $('#roleForm').data('bootstrapValidator')) {
				$('#roleForm').bootstrapValidator(checkValidator);
			}
		});
	});
}
//全选
function chooseAll(){
	var checkBoxAll = $("input[name='roleList']");
	$.each(checkBoxAll,function(j,checkbox){
		$(checkbox).prop("checked",true);
    })
}
//清除全选
function clearAll(){
	 $("[name = roleList]:checkbox").attr("checked", false);
}
//更新数据
function updateRole(){
    var roleId = $('#roleId').val();
	var roleName = $('#roleName').val();
	var roleDesc = $('#roleDesc').val();
	var orgId = $('#orgId').val();	
	var permissionTreeObj = $.fn.zTree.getZTreeObj("permissionTree");
	var node1 = permissionTreeObj.getNodeByParam("PERM_ID", 100);
	var node2 = permissionTreeObj.getNodeByParam("PERM_ID", 201);
	var permissionTreeNodes = permissionTreeObj.getCheckedNodes(true);
	var permId = '';
	for(var i = 0 ; i < permissionTreeNodes.length; i++){
		permId += permissionTreeNodes[i].PERM_ID;
		permId += ",";	
	}
	//获取角色拥有权限“权限管理”时可操作的权限
	var permForPermManageTreeObj = $.fn.zTree.getZTreeObj("permForPermManageTree");
	var permForPermManageNodes = permForPermManageTreeObj.getCheckedNodes(true);
	//当角色拥有权限“权限管理”但是没有选择可操作的权限时弹框提示
	if(node1.checked &&permForPermManageNodes.length<=0){
		alertModel("请选择该角色权限管理时可操作的权限");
		return;
	}else{
		var permForPermManageId = '';
		for(var i = 0 ; i < permForPermManageNodes.length; i++){
			permForPermManageId += permForPermManageNodes[i].PERM_ID;
			permForPermManageId += ",";	
		}
	}
	//获取角色拥有权限“角色管理”时可操作的角色
	 var roleForRoleManageObj = document.getElementsByName("roleList");
	 var roleForRoleManageId = "";
	 for(var i=0; i<roleForRoleManageObj.length; i++){
        if(roleForRoleManageObj[i].checked){
        	roleForRoleManageId += roleForRoleManageObj[i].value;
        	roleForRoleManageId += ",";	
        }
    }
	$.ajax({
		url:"updateSysRole.action",
		data:{
			roleId:roleId,
			roleName:roleName,
			roleDesc:roleDesc,
			orgId:orgId,
			permId:permId,
			permForPermManageId:permForPermManageId,
			roleForRoleManageId:roleForRoleManageId
		},
		dataType:"text",
		type:"POST",
		success:function(data){
			if(data=='success'){
				initFrame();
				permissionTree = null;
				searchTable.ajax.reload();
				alertModel("更新角色成功！")
			}
		},
		error:function(e){
			alertModel("更新角色失败o_o请查明原因后重试！");
		}
	})
}

function delStaff(roleId,roleName,staffId,staffName){
	var attchJson = new Object();
	attchJson.roleId = roleId;
	attchJson.staffId = staffId;
	confirmModel("是否要删除'"+staffName+"'的'"+roleName+"'角色吗？",deleteStaffInRole,attchJson);
}

function selectStaff(){
	$('#staffModal') .modal('show');
	
		$.ajax({
			url : "../gacxOrgController/loadStaffTreeData?t=" + (new Date().getTime()),
			data : {
				"pid" : null
			},
			dataType : "json",
			type : "post",
			success : function(data) {
				// 过滤人员树,将已存在当前角色权限的人员过滤掉
				$.fn.zTree.init($("#stafftree"), setting, data);
				
			}
		})

}

	
	// 设置范围树是否关联下级
	function Branch() {
		if ($("#linkBranch").is(':checked')) {
			var chkboxFather = "ps";
			var chkboxChild = "ps";
			// 设置树的参数
			setting.check.chkboxType = {
					"Y": chkboxFather,
					"N": chkboxChild
				};

		} else {
			var chkboxFather = "";
			var chkboxChild = "";
			setting.check.chkboxType = {
					"Y": '',
					"N": ''
				};
		}
		$.ajax({
			url : "../sysOrgController/loadStaffTreeData?t=" + (new Date().getTime()),
			data : {
				"pid" : null
			},
			dataType : "json",
			type : "post",
			success : function(data) {
				// 过滤人员树,将已存在当前角色权限的人员过滤掉
				$.fn.zTree.init($("#stafftree"), setting, data);
				
			}
		})
	}
function getStaffCheck() {
	var roleId = $("#showStaffInRoleId").val();
	var treeObj = $.fn.zTree.getZTreeObj("stafftree");
	var nodes = treeObj.getCheckedNodes(true);
	var staffs = "";
	for (var i = 0; i < nodes.length; i++) {
		if (false == nodes[i].isParent) {
			staffs+= (nodes[i].id).replace("u","") + ",";
		}
	}
	if(staffs==null||staffs==""){
		alertModel("请选择人员");
		return ;
	}
	
	 $.post('../gacxRoleController/addStaffInRole.action',{'roleId':roleId,'staffs':staffs.substr(0,staffs.length-1)},function(data){
			$('#staffModal') .modal('hide');
			 alertModel("添加人员成功！");
			//  $.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
			 $("#searchStaffTable").DataTable().draw(false); 
		
	 });

}

function deleteStaffInRole(array){
	var roleId =array.roleId;
	var staffId = array.staffId;
	 $.post('../gacxRoleController/deletStaffInRole.action',{'roleId':roleId,'staffId':staffId},function(data){
		 if(data>0){
			 $('#_frm_confirm_modal').modal('hide');
			 alertModel("删除成功！");
			// $.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
			 $("#searchStaffTable").DataTable().draw(false);
		 }
		
	 });
}

//删除数据
function del(roleId,roleName,orgName){
//	confirmModel("是否要删除组织 "+orgName+"下的角色"+roleName+"吗？",deleteSysRole,roleId);//upfc
	confirmModel("是否要删除角色  "+roleName+" 吗？",selectSysRole,roleId);//pms
}
//点删除角色时,需要查看该角色下时候还有人员,如果有,则该角色不可删除,如果没有,则可以删除
function selectSysRole(roleId){
	 $.post('../gacxRoleController/selectStaffInRole.action',{'roleId':roleId},function(data){
		 if(data==null || data.length==0){
			 deleteSysRole(roleId);
		 }else{
			 alertModel("该角色不可删除！");
			
		 }		
	 });
}
//删除角色
function deleteSysRole(roleId){
	 $.post('delSysRole.action',{'roleId':roleId},function(){
		 $('#_frm_confirm_modal').modal('hide');
		 alertModel("删除成功！");
		 searchTable.ajax.reload();
	 });
}
var checkValidator = {
		message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
        	roleName: {
                validators: {
                    notEmpty: {
                        message: '请输入角色名称'
                    }
                }
            },
            orgId: {
            	selector:'#orgName',
            	
                validators: {
                    notEmpty: {
                        message: '请单击选择所属部门'
                    }
                }
            },
            roleDesc:{
            	validators : {
            		 notEmpty: { message: '请输入角色描述'},
    				stringLength: { min: 0, max: 100, message: '请输入不超过100个字符' }
    			}
            }
        },
        submitHandler: function(validator, form, submitButton) {
            // Use Ajax to submit form data
			if($(submitButton).attr('id') == 'addBtn'){
				addRole();
			}
        	if($(submitButton).attr('id') == 'updateBtn'){
				updateRole();
			}
        	
        	
        }

};
function resetValidator(){
	if($('#roleForm').data('bootstrapValidator')){
		$('#roleForm').data('bootstrapValidator').resetForm(false);
	}
}

/**
 * 根据角色ID查询角色拥有的权限，以树的形式在模态框中展示
 * @param roleId 角色ID
 * @param roleName 角色名
 * @returns
 */
function searchPerm(roleId, roleName){
	$("#permModalLabel").text("\"" + roleName + "\"" +" 角色的权限");
	var permNum = 0;
	$.post("getRolePerm",{"roleId":roleId},function(data){
		permTree = $.fn.zTree.init($("#permissionTree1"), permissionViewSetting, data.rolePerm);
		permTree.expandAll(true);
	});
	$('#roleHavepermModal').modal('show');
}



/**
 * 根据角色ID查询拥有此角色的人员
 * @param roleId 角色ID
 * @param roleName 角色名
 * @returns
 */
function searchStaff(roleId, roleName){
	$("#showStaffInRoleId").val(roleId);
	$('#roleManage').show();
	$('#searchContent').hide();
	$('#RoleContainer').show();
	$(".ma_tip").text("拥有"+"\"" + roleName + "\"" +" 角色的人员");
	$("#searchStaffTable").DataTable().destroy();
	$("#searchStaffTable").DataTable({
		"ordering": false,// 排序
		"serverSide": true,// 开启服务器模式
		"scrollX": true,// 横向滚动     
		autoWidth:false,
		ajax: {
            "type": "POST",
            "url":'getRoleStaff.action',//请求路径
            "contentType": 'application/x-www-form-urlencoded; charset=UTF-8',
            "dataType":'json',
            "data":{"roleId":roleId} 
		},           
		columns: [// 对应列
			{"data":null, visible:false},
	        {"data": "STAFF_NAME",title:"人员姓名",className: "text-center",render:function(a,b,c,d){
	        	return "<a href=\"javascript:staffDetails('"+c.STAFF_ID+"')\">"+a+"</a>";}},
	        {"data": "LOGIN_NAME",title:"账号",className: "text-center"},
	        {"data": "ORG_NAME",title:"组织名称",className: "text-center"},
	        {"data": "SEX",title:"性别",className: "text-center",render: function (a, b, c, d) {
                if('M' == c.SEX){
                	return '男';
                }else{
                	return '女';
                }
            }},
	        {"data": "MOBLE_PHONE",title:"手机号码",className: "text-center"},
	        {"data": "EMAIL",title:"邮箱",className: "text-center"},
	        {"data": "PHONE",title:"电话",className: "text-center"},
	        {"data": "STAFF_STATUS",title:"岗位状态",className: "text-center", render: function (a, b, c, d) {
                if('1' == c.STAFF_STATUS){
                	return '有效';
                }else{
                	return '无效';
                }
            }},
            {"data": null,title:"操作",className: "text-center","width":"20%",render: function (a, b, c, d) {
	        	 var context = addRoleStaffbtnFun(roleId,roleName,c);
	             var html = template(context);
	             return html;
	        }
           }
	    ],
	    "columnDefs": [
			{// 所有列默认值
				"targets": "_all",
				"defaultContent": '',
				render: $.fn.dataTable.render.ellipsis(22, true)
			}],
		    lengthMenu: [
		    	menuLength,
		    	menuLength
		    ],
		"dom": 'rt<"pull-left mt5"l><"pull-left mt5"i><"pull-right mt5"p><"clear">' //生成样式
	});
	
}

//展示人员信息
function staffDetails(staffId){
	var url = prc + "/sysStaffController/goStaffInfo?staffId="+staffId;
	$("#jump_url").attr("src", url);
	$('#infoModal').modal({
		'show' : true
	});
}




//角色人员删除操作配置

function addRoleStaffbtnFun(roleId,roleName,c){
	contentBtn = "";
	if(contentBtn){
		return contentBtn;
	}else{
		var btnArray = new Array();
		if(hadPermission.getStaff){
			btnArray.push({"name": "删除", "fn": "delStaff(\'" + roleId + "\', \'"+ roleName +"\',\'" + c.STAFF_ID + "\', \'"+ c.STAFF_NAME +"\')"});
		}

		contentBtn = {
			func:btnArray
		}
		return contentBtn;
	}
	
	
	
	
}